package midas.mw.crt;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;

import midas.mw.cfg.CfgError;
import midas.mw.cfg.CfgLogging;
import midas.mw.cfg.log.Logger;
import midas.mw.crt.MD.PriorityTable;
import midas.mw.crt.common.IPMessage;
import midas.mw.crt.interfaces.CrtCallback;
import midas.mw.crt.presence.PresenceKey;

/**
 * This class manages the thread responsible of sending messages
 */
public class NokiaNodesPresenceThreadMessages extends Thread
{
    /**
	 * Instance of the CRT running in the node
	 */
	CrtImpl crt = null;
	
	/**
	 * Time to wait for a response
	 */
	private long waitingTime 		= 30000;
	
	
	private Hashtable presenceTable 		= null;
	/**
	 * Constructor - initiate local variables
	 * @param crt Instance of the CRT running in the node
	 */
	public NokiaNodesPresenceThreadMessages (CrtImpl crt)
	{		
		CfgLogging.logEvent(CfgLogging.LOG_MCALL, Logger.COMPONENT_CRT, CfgLogging.SEV_DEBUG, "NokiaNodesPresenceThread(CrtImpl)");		
		
		this.crt 			= crt;		
	}
	
	/**
	 * Overriding the run method of class Thread
	 */
	public void run()
	{
		CfgLogging.logEvent(CfgLogging.LOG_MCALL, Logger.COMPONENT_CRT, CfgLogging.SEV_DEBUG, "NokiaNodesPresenceThread.run()");		
        
		byte [] data = new byte [1];
		data[0] = 0;
		IPMessage ipMessage = new IPMessage(crt.getOwnNodeId() ,null, "", "", data);
		ipMessage.setMessageType(Constants.IP_MESSAGE_PRESENCE);
		
		presenceTable = new Hashtable();
		
		while (true)
		{
			//Compruebo los nodos Nokia que controlo y les mando un mensaje de confirmacion de presencia
			Vector nokiaNodes = crt.getNodeIdentifierSolver().getOwnJXMENodes();
			String nodeName   = null;
			for (int i=0; i<nokiaNodes.size(); i++)
			{
				nodeName = (String)nokiaNodes.get(i); 
				System.out.println("NOMBRE: " + nodeName);
				presenceTable.put(nodeName, new Boolean(false));
				ipMessage.setDestinationNodeId(nodeName);
				try {
					crt.getJxtaPlatform().forwardMessage(ipMessage); 
				} catch (CrtException crt){
					crt.printStackTrace();
				}
			}
			
			//ipMessage = null;
			
			try {
				sleep(waitingTime);
			} catch (InterruptedException ie){ie.printStackTrace();}
			
			//Comprobamos los que ha recibido
			Iterator it = presenceTable.entrySet().iterator(); 
			while (it.hasNext())
			{
				Map.Entry entry = (Map.Entry)it.next();
				if (!((Boolean)entry.getValue()).booleanValue())
				{
					//Se lo mando al resto de los nodos
					String jxtaId = (String)crt.getNodeIdentifierSolver().getJxtaConnectedPeers().get(entry.getKey());
					//crt.getJxtaPlatform().getNodePresence().getMIDASNode().get(jxtaId);
					String cadenaPresenceKey = jxtaId + "," + (String)entry.getKey() + "," +  Constants.NOKIA_USER_NODE + "," + crt.getOwnNodeId() + ",0";		
					PresenceKey presenceKey = PresenceKey.create(cadenaPresenceKey);
					//crt.getJxtaPlatform().getNodePresence().removePeer((PresenceKey)crt.getJxtaPlatform().getNodePresence().getMIDASNode().get(jxtaId));
					crt.getJxtaPlatform().getNodePresence().announceLeave(presenceKey);
					System.out.println(entry.getKey() + " HA DESAPARECIDO");
				}
				else
					System.out.println(entry.getKey() + " TODAVIA ESTA");
					
			}
			
			try {
				sleep(60000);
			} catch (InterruptedException ie){ie.printStackTrace();}
			
			presenceTable.clear();
		}								
	}	
	
	public void isPresent (String nodeName)
	{
		if (presenceTable.containsKey(nodeName))
			presenceTable.put(nodeName, new Boolean(true));
	}
}
